package com.scau.classOnline.controller;

import com.scau.classOnline.common.DateUtil;
import com.scau.classOnline.common.TimetableStyle;
import com.scau.classOnline.common.UserUtils;
import com.scau.classOnline.dto.CourseDTO;
import com.scau.classOnline.dto.CourseScheduleDTO;
import com.scau.classOnline.dto.ScheduleDTO;
import com.scau.classOnline.entity.User;
import com.scau.classOnline.model.CourseDetailModel;
import com.scau.classOnline.model.RespEntity;
import com.scau.classOnline.model.UserTakeModel;
import com.scau.classOnline.service.CourseService;
import com.scau.classOnline.service.ScheduleService;
import com.scau.classOnline.sftp.FTPClient;
import com.scau.classOnline.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/course")
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private FTPClient ftpClient;

    @GetMapping(value = "/stuSchedule")
    public RespEntity getStuSchedule(Integer offset) {
        int id = UserUtils.getCurrentUser().getId();
        Date day = DateUtil.getDay(offset);
        Integer highlightWeek = null;
        if (offset == 0) {
            int today = DateUtil.getWeekOfDay(new Date());
            if (today == 0) {
                today = 7;
            }
            highlightWeek = today;
        }
        String[][] timetableType = TimetableStyle.timetableType;
        String[] week = TimetableStyle.week;
        String[][] courseList = courseService.getSchedule(id, day, timetableType.length, TimetableStyle.week.length);
        Map<String, Object> map = new HashMap<>();
        map.put("courseList", courseList);
        map.put("highlightWeek", highlightWeek);
        map.put("week", TimetableStyle.week);
        map.put("timetableType", timetableType);
        return RespEntity.ok("课表查询成功", map);
    }

    @RequestMapping(value = "/teaSchedule")
    public RespEntity getTeaSchedule(Integer offset) {
        int id = UserUtils.getCurrentUser().getId();
        Date day = DateUtil.getDay(offset);
        Integer highlightWeek = null;
        if (offset == 0) {
            int today = DateUtil.getWeekOfDay(new Date());
            if (today == 0) {
                today = 7;
            }
            highlightWeek = today;
        }
        String[][] timetableType = TimetableStyle.timetableType;
        String[] week = TimetableStyle.week;
        String[][] courseList = courseService.getTeaSchedule(id, day, timetableType.length, week.length);
        Map<String, Object> map = new HashMap<>();
        map.put("courseList", courseList);
        map.put("highlightWeek", highlightWeek);
        map.put("week", week);
        map.put("timetableType", timetableType);
        return RespEntity.ok("课表查询成功", map);
    }

    @PostMapping(value = "/finish")
    public RespEntity finish(Integer id){
        int i = courseService.setFinished(id);
        if (i == 1){
            return getCourses();
        }else if (i == 0){
            return RespEntity.error("更新失败！");
        }else {
            return RespEntity.error("该课程不存在！");
        }
    }

    /**
     * get方法
     * 数据格式：'url?id=1'
     * 课程详情
     *
     * @param id
     * @return
     */
    @GetMapping("/detail")
    private RespEntity getCourseDetailById(@RequestParam("id") Integer id) {
        scheduleService.updateAllByTime();
        return RespEntity.ok(courseService.getCourseDetailById(id));
    }

    /**
     * 修改课程，和下面添加课程一样
     * <p>
     * 只能使用表单提交，设置 processData:false , mimeType=multipart/form-data
     * js代码例子：
     * var tid=1;
     * var title="语文";
     * var info="真的假";
     * var scheduleList=[
     * {"timeId": 1,"date":"2019-08-02","title":"古诗文阅读"},
     * {"timeId": 2,"date": "2019-07-09","title":"文言文赏析"}
     * ]; //这是一个对象数组
     * <p>
     * var schedules=JSON.stringify(scheduleList); //对象数组转成JSON字符串
     * var file = document.getElementById("file").files[0];
     * <p>
     * var formData = new FormData();
     * formData.append("tid",tid);
     * formData.append("title",title);
     * formData.append('info',info);
     * formData.append('schedules',schedules);
     * formData.append('pic', file);
     *
     * @param pic       可以不上传图片，旧的图片url不会被空值覆盖
     * @param courseDTO
     * @return
     */
    @PostMapping("/update")
    private RespEntity modifyCourseById(@RequestParam(value = "pic", required = false) MultipartFile pic,
                                        CourseDTO courseDTO) {
        if (pic != null) {
            String url = uploadPic(pic);
            courseDTO.setIconUrl(url);
        }
        return RespEntity.ok(courseService.modifyCourseById(courseDTO));
    }

    @PostMapping("/add")
    private RespEntity addCourse(@RequestParam("pic") MultipartFile pic, HttpServletRequest request) {
        CourseScheduleDTO courseScheduleDTO = convertToScheduleDTO(request);
        String url = uploadPic(pic);
        courseScheduleDTO.setIconUrl(url);
        return RespEntity.ok(courseService.addCourse(courseScheduleDTO));
    }

//cid插入数据库中全变成0
    @PostMapping("/take")
    private RespEntity takeCourse(@RequestBody Map<String,Object> map) {
        Integer sid= (Integer) map.get("sid");
        Integer cid= (Integer) map.get("cid");
        if (courseService.bookCourse(sid, cid) == 1) {
            return RespEntity.ok("课程订阅成功！");
        } else {
            return RespEntity.error("课程订阅失败！");
        }
    }

    @PostMapping("/cancel")
    private RespEntity cancelCourse(@RequestBody Map<String,Object> map) {
        Integer sid= (Integer) map.get("sid");
        Integer cid= (Integer) map.get("cid");
        if (courseService.cancelCourse(sid, cid) == 1) {
            return RespEntity.ok("取消订阅成功！");
        } else {
            return RespEntity.error("取消订阅失败！");
        }
    }

    @GetMapping("/getBookCourse")
    private RespEntity getBookCourse(@RequestParam("sid")Integer sid,
                                     @RequestParam("cid")Integer cid){
        return RespEntity.ok(courseService.getBookCourse(sid,cid));
    }

    @GetMapping("/list")
    private RespEntity getCoursesByPages(@RequestParam("start") Integer start,
                                         @RequestParam("count") Integer count) {
        return RespEntity.ok(courseService.getCoursesByPages(start, count));
    }

    @GetMapping("/search")
    private RespEntity search(@RequestParam("pattern") String pattern) {
        return RespEntity.ok(courseService.getCoursesByFuzzy(pattern));
    }

    @GetMapping("/getCourses")
    private RespEntity getCourses(){
        User user = UserUtils.getCurrentUser();
        if (user.getStatus() == 0){
            List<UserTakeModel> courses = courseService.getCourseByStuId(user.getId());
            return RespEntity.ok("查询成功！",courses);
        } else if (user.getStatus() == 1){
            List<CourseDetailModel> courses = courseService.getCourseByTeaId(user.getId());
            return RespEntity.ok("查询成功！",courses);
        }
        return RespEntity.error("查询失败！");
    }

    private String uploadPic(MultipartFile pic) {
        String picPath = ftpClient.getRemotePicPath();
        String picName = pic.getOriginalFilename();
        picName=System.currentTimeMillis()+picName.substring(picName.lastIndexOf("."));//当前时间毫秒+文件后缀名
        String picRoute = picPath.substring(picPath.lastIndexOf("/"));
        ftpClient.upload(pic, picPath, picName);
        return "http://" + ftpClient.getHost() + picRoute + "/" + picName;
    }

    private CourseScheduleDTO convertToScheduleDTO(HttpServletRequest request) {
        CourseScheduleDTO courseScheduleDTO = new CourseScheduleDTO();
        String uid = request.getParameter("uid");
        courseScheduleDTO.setUid(Integer.valueOf(uid));
        String title = request.getParameter("title");
        courseScheduleDTO.setTitle(title);
        String info = request.getParameter("info");
        courseScheduleDTO.setInfo(info);
        String schedules = request.getParameter("schedules");
        List<ScheduleDTO> scheduleDTOList = JsonUtil.stringToList(schedules, ScheduleDTO.class);
        courseScheduleDTO.setScheduleDTOList(scheduleDTOList);
        return courseScheduleDTO;
    }
}
